//
//  FQDColumnFeedCell.m
//  FakeQDaily
//
//  Created by mewxiv on 8/28/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDColumnFeedCell.h"
#import "FQDFeedCellTitleBarView.h"
#import "FQDColumnArticleCell.h"
#import "MJRefreshAutoFooter.h"
#import "FQDColumnArticleFeedCellItemProvider.h"
#import "FQDArticleDetailViewController.h"
#import "FQDColumnFeedCellItem.h"
#import "FQDRegularFeedCellItem.h"
#import "FQDSubscribeManager.h"
#import "FQDRestModel.h"
#import "QDailyAPI.h"

#import "Masonry/Masonry.h"
#import "UIImageView+WebCache.h"
#import "YYModel.h"

static CGFloat const FQDColumnLoadingMoreInset = 80.0f;

@interface FQDColumnFeedCell () <UICollectionViewDelegate,
                                 UICollectionViewDataSource,
                                 UICollectionViewDelegateFlowLayout,
                                 UIScrollViewDelegate>

@property (nonatomic, strong) FQDFeedCellTitleBarView *titleBarView;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) UICollectionView *articleCollectionView;
@property (nonatomic, strong) FQDColumnArticleFeedCellItemProvider *provider;

@end

@implementation FQDColumnFeedCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        _provider = [[FQDColumnArticleFeedCellItemProvider alloc] init];
        [self setupTitleBarView];
        [self setupArticleCollectionView];
        [self prepareConstraints];
        [self setupNotifications];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)prepareForReuse
{
    [super prepareForReuse];
    self.articleCollectionView.contentOffset = CGPointZero;
}

- (void)setupTitleBarView
{
    _titleBarView = [[FQDFeedCellTitleBarView alloc] init];
    [self.contentView addSubview:_titleBarView];
    
    [_titleBarView.titleBarButton addTarget:self action:@selector(titleBarTapped:)
                           forControlEvents:UIControlEventTouchUpInside];
    [_titleBarView.followButton addTarget:self action:@selector(followColumn:)
                         forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)setupArticleCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 5.0f;
    flowLayout.itemSize = CGSizeMake(278, 265);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _flowLayout = flowLayout;
    
    _articleCollectionView =
    [[UICollectionView alloc] initWithFrame:self.contentView.bounds
                       collectionViewLayout:flowLayout];
    _articleCollectionView.backgroundColor = [UIColor whiteColor];
    _articleCollectionView.showsHorizontalScrollIndicator = NO;
    _articleCollectionView.showsVerticalScrollIndicator = NO;
    _articleCollectionView.delaysContentTouches = YES;
    _articleCollectionView.canCancelContentTouches = YES;
    _articleCollectionView.multipleTouchEnabled = YES;
    _articleCollectionView.delegate = self;
    _articleCollectionView.dataSource = self;
    _articleCollectionView.contentInset = UIEdgeInsetsMake(0, 10.0f, 0, 0);
    [self.contentView addSubview:_articleCollectionView];
    
    [_articleCollectionView registerClass:[FQDColumnArticleCell class]
               forCellWithReuseIdentifier:[FQDColumnArticleCell reuseId]];
    
}

- (void)prepareConstraints
{
    WeakSelf;
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(weakSelf);
        make.height.equalTo(@335);
    }];
    
    [_titleBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.left.equalTo(weakSelf.contentView);
        make.width.equalTo(weakSelf.contentView);
        make.height.equalTo(@50);
    }];
    
    [_articleCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(weakSelf.contentView);
        make.bottom.equalTo(weakSelf.contentView).offset(-10);
        make.height.equalTo(@265);
    }];
}

- (void)setupNotifications
{
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(subscribeColumnChanged:)
                          name:FQDSubscribeColumnsDidChangeNotification object:nil];
}

- (void)configureCellWithCellItem:(FQDColumnFeedCellItem *)cellItem
{
    [super configureCellWithCellItem:cellItem];
    
    [self updateColumn];
}

- (void)updateColumn
{
    FQDColumnFeedCellItem *cellItem = (FQDColumnFeedCellItem *)self.cellItem;
    FQDColumn *column = cellItem.column;
    BOOL subscribed = [[FQDSubscribeManager sharedManager] hasSubscribedColumn:column.ID];
    self.titleBarView.followed = subscribed;
    [self.titleBarView.iconView sd_setImageWithURL:[NSURL URLWithString:column.icon]];
    [self.titleBarView.titleLabel setText:column.name];
    
    self.provider.feedId = column.ID;
    [self loadNewCellItems];
}

- (void)updateLoadingMoreUI
{
    UIEdgeInsets inset = self.articleCollectionView.contentInset;
    if ([self.provider hasMoreCellItems]) {
        inset.right = FQDColumnLoadingMoreInset;
    } else {
        inset.right = 0;
    }
    self.articleCollectionView.contentInset = inset;
}

#pragma mark - Networking

- (void)loadNewCellItems
{
    [self.provider loadNewCellItems:^(BOOL isSuccess) {
        [self updateLoadingMoreUI];
        [self.articleCollectionView reloadData];
    }];
}

- (void)loadMoreCellItems
{
    [self.provider loadMoreCellItems:^(BOOL isSuccess) {
        [self updateLoadingMoreUI];
        [self.articleCollectionView reloadData];
    }];
}

#pragma mark - Event response
- (void)titleBarTapped:(UIButton *)button
{
    if ([self.delegate respondsToSelector:@selector(collectionViewCell:actionType:actionControl:userInfo:)]) {
        [self.delegate collectionViewCell:self actionType:FQDColumnFeedCellActionTitleBarClicked
                            actionControl:button userInfo:nil];
    }
}

- (void)followColumn:(UIButton *)button
{
    FQDSubscribeManager *subscribeManager = [FQDSubscribeManager sharedManager];
    FQDColumnFeedCellItem *columnCellItem = (FQDColumnFeedCellItem *)self.cellItem;
    [subscribeManager toggleSubscribeColumn:columnCellItem.column.ID
     completion:^(BOOL success, BOOL subscribed) {
        if (success) {
            [self updateColumn];
        }
    }];

}

#pragma mark - Notifications
- (void)subscribeColumnChanged:(NSNotification *)note
{
    [self updateColumn];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat scrollMaxX = scrollView.contentOffset.x + scrollView.frame.size.width;
    if (scrollView.isDragging && scrollMaxX > scrollView.contentSize.width) {
        if (![self.provider isLoadingCellItems] && [self.provider hasMoreCellItems]) {
            [self loadMoreCellItems];
        }
    }
}

#pragma mark - Collection View DataSource Methods
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.provider.cellItems count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FQDRegularFeedCellItem *cellItem = self.provider.cellItems[indexPath.row];
    
    FQDColumnArticleCell *cell = (FQDColumnArticleCell *)
    [collectionView dequeueReusableCellWithReuseIdentifier:[FQDColumnArticleCell reuseId]
                                              forIndexPath:indexPath];
    cell.cellItem = cellItem;
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    FQDRegularFeedCellItem *cellItem = self.provider.cellItems[indexPath.row];
    FQDArticleDetailViewController *articleDetailVC = [[FQDArticleDetailViewController alloc] init];
    articleDetailVC.post = cellItem.feed.post;
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UINavigationController *navController = (UINavigationController *)window.rootViewController;
    [navController pushViewController:articleDetailVC animated:YES];
}

#pragma mark - Getters and Setters
- (void)setCellItem:(FQDColumnFeedCellItem *)cellItem
{
    FQDColumnFeedCellItem *oldCellItem = (FQDColumnFeedCellItem *)self.cellItem;
    if (![oldCellItem.column.ID isEqualToString:cellItem.column.ID]) {
        [self.articleCollectionView setContentOffset:CGPointZero];
    }
    
    [super setCellItem:cellItem];
}

+ (NSString *)reuseId
{
    return @"FQDColumnFeedCellId";
}

@end
